package a09_贪心算法;

import java.util.Arrays;
import java.util.stream.IntStream;

//两次贪心
//1、
public class a09_K次取反后最大化的数组和复习1 {

    public static void main(String[] args) {
        //2,-3,-1,5,-4
        int[] nums = new int[]{2,-3,-1,5,-4};
        largestSumAfterKNegations(nums, 2);
    }
    public static int largestSumAfterKNegations(int[] nums, int k) {
        nums = Arrays.stream(nums)
                .boxed()
                .sorted((item1, item2) -> Math.abs(item2) - Math.abs(item1))
                .mapToInt(Integer::intValue).toArray();

        for (int i = 0; i < nums.length; i++) {
            if(nums[i] < 0 && k > 0){
                nums[i] = nums[i] * -1;
                k--;
            }
        }

        if(k > 0){
            if (k % 2 != 0) {
                nums[nums.length - 1] = nums[nums.length - 1] * -1;
            }
        }
        return Arrays.stream(nums).sum();
    }
}
